package com.edfeff.bio.http;

import com.edfeff.bio.SimpleHttpServer;

import java.io.IOException;
import java.net.Socket;
import java.util.List;

public class HttpHandler implements Runnable {
    private final SimpleHttpServer server;
    private final Socket client;
    private final InputBuffer inputBuffer;
    private final OutputBuffer outputBuffer;
    private final Request request;
    private final Response response;

    public HttpHandler(SimpleHttpServer server, Socket client) {
        this.server = server;
        this.client = client;
        this.request = new Request();
        this.response = new Response();
        this.inputBuffer = new InputBuffer(this.request);
        this.outputBuffer = new OutputBuffer(this.response);
    }

    @Override
    public void run() {
        try {
            inputBuffer.setInputStream(client.getInputStream());
            outputBuffer.setOutputStream(client.getOutputStream());

            //读取请求行
            inputBuffer.parseRequestLine();
            //读取请求头部
            inputBuffer.parseHeaders();
            //校验请求头部
            prepareAndCheckRequest();
            //读取请求体
            inputBuffer.parseRequestBody();

            //准备响应体
            prepareResponse();

            //转发给适配器处理
            server.getAdapter().service(request, response);

        } catch (Throwable e) {
            handleError(e);
        } finally {
            //类似http0.9协议 不支持长连接
            try {
                outputBuffer.endRequest();
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void prepareResponse() {
        List<Header> headers = response.getHeaders();
        headers.add(new Header("server", "edfeff"));
    }

    private void handleError(Throwable error) {
        error.printStackTrace();
        int code = 400;
        if (error instanceof StsException) {
            StsException stsException = (StsException) error;
            code = stsException.getCode();
        }
        response.setStatus(code);
    }

    private void prepareAndCheckRequest() {
        //准备request对象
        request.setStartTime(System.currentTimeMillis());
        //仅支持http协议
        if (!request.getProtocol().toUpperCase().startsWith("HTTP/")) {
            throw new StsException(505, "不支持的HTTP版本");
        }
        //不支持多文件协议
        String contentType = request.getContentType();
        if (contentType != null && contentType.contains("multipart")) {
            throw new StsException(400, "不支持的内容类型");
        }
    }
}
